package com.tbit.main.remote.sms;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

/**
 * 车卫士短信网关
 *
 * @author Leon
 * 2015-8-28 下午05:29:38
 */
@Slf4j
public class CWSMmsHttpClient {
    /**
     * 接入密钥
     */
    private static final String secret = "tbit36987";
    private static HttpClient client = null;

    /**
     * 维持单session
     */
    public static HttpClient getClient() {
        if (client == null) {
            MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
            client = new HttpClient(connectionManager);
            /**设置编码*/
            client.getParams().setContentCharset("UTF-8");
            /**请求超时*/
            client.getHttpConnectionManager().getParams().setConnectionTimeout(1000);
            /**读取超时*/
            client.getHttpConnectionManager().getParams().setSoTimeout(5000);
        }
        return client;
    }

    /**
     * 抓取数据
     */
    public static void sendSms(String phone, String content) {
        log.info("phone=" + phone + ",content=" + content);

        HttpClient client = getClient();
        PostMethod post = null;

        try {
            post = new PostMethod("http://www.cheweishi.cn/smsAction!gpsSendSms.do");
            NameValuePair phonePair = new NameValuePair("phone", phone);
            NameValuePair contentPair = new NameValuePair("content", content);
            NameValuePair secretPair = new NameValuePair("secret", secret);
            post.setRequestBody(new NameValuePair[]{phonePair, contentPair, secretPair});
            client.executeMethod(post);
            String result = post.getResponseBodyAsString();
            boolean res = JSON.parseObject(result).getBoolean("res");
            if (!res) {
                log.error(result);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            post.releaseConnection();
        }
    }

    public static void main(String[] args) {
        sendSms("13414983507", "[优驱出行]请尽快还车并付费，如果发现属于恶意用车，我们将做报警处理。谢谢");
    }
}